package com.nenude.corejava.ch13.homework;

/**
 *------不使用线程：
 *
 * JAVA多线程编程。 用JAVA写一个多线程程序，如写四个线程，二个加1， 二个对一个变量减一，输出
 *
 * @author admin
 *
 */
public class HomeWork1 {
	private int count = 0;

	// 相加
	public  void add() {
		count++;
	}

	// 相减
	public  void desc() {
		count--;
		
	}

	// 设计两个线程类（内部类）
	
	//-----相减
	class AddClass implements Runnable {
		private int threadId = 0;

		public AddClass(int id) {
			this.threadId = id;
		}
		@Override
		public void run() {
			for (int i = 0; i < 50; i++) {
				add();
				System.out.println(threadId + ", " + count);
			
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	//-----相减-内部线程类
	class DescClass implements Runnable {
		private int threadId = 0;

		public DescClass(int id) {
			this.threadId = id;
		}
		@Override
		public void run() {
			//控制循环次数
			for (int i = 0; i < 50; i++) {
				desc();
				System.out.println(threadId + " " + count);
				
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	//---测试类
   public static  void main(String [] args) {
		//实例化
	HomeWork1 homeWork=new  HomeWork1();
	
	//id是1
	 AddClass addClass1=homeWork.new AddClass(1);
	 AddClass addClass2=homeWork.new AddClass(2);
	
	 DescClass descClass1=homeWork.new DescClass(3);
	 DescClass descClass2=homeWork.new DescClass(4);

	/* //开线程:线程组（当批量使用线程时）
	 ThreadGroup threadGroup=new ThreadGroup("demo");*/
	 
	 new Thread(addClass1).start();
	 new Thread(addClass2).start();
	 new Thread(descClass1).start();
	 new Thread(descClass2).start();	 
	}
	

}
